package com.oritsh.dicom.utils.adaptor;

import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.oritsh.dicom.utils.DataSetHelper;
import org.dcm4che.data.*;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: zarra
 * Date: 14-2-5
 * Time: 下午5:26
 * Copyright Shanghai Orient Rain Information Technology Co.,Ltd.
 */
public class JsonAdaptorHelper {

    static ElementDictionary elementDictionary  =
            StandardElementDictionary.getStandardElementDictionary();

    static public Type gsonDataType(){
        Type dataType = new TypeToken< Map<String, Object> >(){}.getType();
        return dataType;
    }

    static public Map<String,Object> attributesToMap(Attributes src){
        Map<String, Object> map = new HashMap<String, Object>();
        for(int tag:src.tags()){
            String tagName = elementDictionary.keywordOf(tag);
            VR vr = elementDictionary.vrOf(tag);
            Object value = src.getValue(tag);

            if(vr.isStringType()){
                value = src.getString(tag);
            }else if(vr.isIntType()){
                value = src.getInt(tag, Integer.MIN_VALUE);
            }
            map.put(tagName, value);
        }
        return map;
    }

    static public Attributes mapToAttributes(Map<String,Object> map){
        Attributes attributes = new Attributes();
        for(Map.Entry<String, Object> entry:map.entrySet()){
            String key = entry.getKey();
            Object value = entry.getValue();
            int tag = elementDictionary.tagForKeyword(key);
            VR vr = elementDictionary.vrOf(tag);
            DataSetHelper.putValueToDataSet(attributes,tag,value);
        }
        return attributes;
    }

    static public GsonBuilder gsonBuilder(){
        GsonBuilder builder = new GsonBuilder();
        builder.serializeNulls();
        builder.registerTypeAdapter(Attributes.class, new AttributesGsonAdaptor());
        return builder;
    }

    static public Gson gson(){
        return gsonBuilder().create();
    }

    static public Module jacksonModule(){
        SimpleModule module = new SimpleModule("ORITSH.Dicom", new Version(1, 0, 0, null,"com.oritsh.dicom","dicom-core"));
        module.addSerializer(Attributes.class,new AttributesJacksonSerializer());
        module.addDeserializer(Attributes.class,new AttributesJacksonDeserializer());
        return module;
    }

    static public ObjectMapper objectMapper(){
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(jacksonModule());
        return mapper;
    }
}
